#include "Diamond.h"
#include "GameManager.h"
#include <time.h> 
#include <string>

namespace King {
	static const float DIAMOND_WIDTH = 40.0f;
	static const float DIAMOND_HEIGHT = 40.0f;

	DiamondIndex DiamondIndex::NULLINDEX(-1, -1);

	bool DiamondIndex::operator == (const DiamondIndex& index) const
	{
		return col == index.col && row == index.row;
	}

	bool DiamondIndex::operator != (const DiamondIndex& index) const
	{
		return col != index.col || row != index.row;
	}

	bool DiamondIndex::operator < (const DiamondIndex& index) const
	{
		if (col < index.col)
		{
			return true;
		}
		else if (col == index.col)
		{
			return row < index.row;
		}

		return false;
	}

	bool DiamondIndex::isNeighborhood(const DiamondIndex& index) const
	{
		int xSpan = abs(col - index.col);
		int ySpan = abs(row - index.row);
		return (xSpan == 1 && ySpan == 0) 
			|| (ySpan == 1 && xSpan == 0);
	}

	bool DiamondIndex::isValid() const
	{		
		int colMax = GameManager::getInstance().getColMax();
		int rowMax = GameManager::getInstance().getRowMax();
		assert(col <= colMax && col >= 0);
		assert(row <= rowMax && row >= 0);

		if (col < 0 || col > colMax)
		{
			return false;
		}

		if (row < 0 || row > rowMax)
		{
			return false;
		}

		return true;
 
	}
	
	Diamond::~Diamond()
	{
	}

	Diamond::Diamond()
    : mIndex(-1, -1)
	{
	}

	Diamond::Diamond(const DiamondIndex& index)
	{
		if (!index.isValid())
		{
			throw std::runtime_error(std::string("Invalid index value!")); 
		}

		setIndex(index);

		mColor = static_cast<Engine::Texture>(rand() % Engine::Texture::TEXTURE_LAST_COLOR + 1);
	}

	DiamondPoint Diamond::getPosition() const
	{
		DiamondPoint position;
		position.x = mBBox.origin.x;
		position.y = mBBox.origin.y;

		return position;
	}

	Engine::Texture	Diamond::getColor() const
	{
		return mColor;
	}

	bool Diamond::containsPoint(const DiamondPoint& point)
	{
		if (point.x > mBBox.origin.x + mBBox.w
		||	point.x < mBBox.origin.x)
		{
			return false;
		}

		if (point.y > mBBox.origin.y +mBBox.h
		||	point.y < mBBox.origin.y)
		{
			return false;
		}

		return true;
	}

	void Diamond::setIndex(const DiamondIndex& index)
	{
		assert(index.isValid());
		if (!index.isValid())
		{
			return;
		}
		mIndex = index;
		mBBox.origin.x = mIndex.col * DIAMOND_WIDTH;
		mBBox.origin.y = mIndex.row * DIAMOND_HEIGHT;
		mBBox.w = DIAMOND_WIDTH;
		mBBox.h = DIAMOND_HEIGHT;

	}
}

